import React from 'react';
import {Row, Col, Icon, Card, Button, Form, Select, Cascader, Modal} from 'antd';
import ApiTubro from '@/components/Engineering/ApiTubro';
// import SearchControl from '@/components/Engineering/SearchControl';
import ETable from '@/components/Engineering/ETable';
import Utils from '@/components/Engineering/utils';
import axios from '@/components/Engineering/axios';
import AutoSearch from './components/auto-select';

import {PageHeaderWrapper} from '@ant-design/pro-layout';
import {connect} from 'dva';
import Localfees from '@/pages/manage/logistics/components/localfees';

const FormItem = Form.Item;

@connect(({loading, searchList}: any) => ({
  searchList,
  loading: loading.models.rule,
}))
class trailerTransport extends React.Component {
  state = {
    transportDefaultType: 'trailerTransport', //运输类型默认值
    cascaderOptions: [], //级联的参数
    insuranceCurrencyList: [],

    searchFieldList: [
      {
        type: 'SELECT',
        label: '运输类型',
        field: 'transportType',
        placeholder: '请输入运输类型',
        initialValue: 'trailerTransport',
      },
    ],
  };
  page = {};
  expand = false;

  Columns = [
    {
      title: '起运港/目的港',
      dataIndex: 'changxian',
      key: 'chuanxian',
      render: (text: any, record: any) => (
        <div>
          {record.loadingEnName}({record.loadingName}) — {record.destinationEnName}(
          {record.destinationName})
        </div>
      ),
    },
    {title: '航线', dataIndex: 'airlineName', key: 'airlineName'},
    {title: '船公司', dataIndex: 'berthingName', key: 'berthingName'},
    {title: '船期', dataIndex: 'cut_off', key: 'cut_off'},
    {title: '航程', dataIndex: 'sail', key: 'sail'},
    {title: '20GP', dataIndex: 'fee20gp', key: 'fee20gp'},
    {title: '40GP', dataIndex: 'fee40gp', key: 'fee40gp'},
    {title: '40HC', dataIndex: 'fee40hq', key: 'fee40hq'},
    {
      title: '有效期',
      dataIndex: 'time',
      key: 'time',
      render: (text, record) => (
        <p>
          {record.begindate} - {record.enddate}
        </p>
      ),
    },
    {
      title: '附加费用',
      dataIndex: 'DDU',
      key: 'DDU',
      render: (text, record) => (
        <a
          onClick={() => {
            this.setState({localFeeListVisable: true});
            this.getlocalfee({id: record.id});
          }}
        >
          本地费
        </a>
      ),
    },
    {
      title: '操作',
      dataIndex: 'caozuo',
      key: 'caozuo',
      render: (text, record) => {
        return (
          <div>
            <a
              onClick={() => {
                this.props.history.push({
                  pathname: '/service/logistics/trailer-online-booking',
                  query: record,
                });
              }}
            >
              <Icon type="edit" style={{marginRight: 2}}/>
              在线订舱
            </a>
          </div>
        );
      },
    },
  ];

  componentDidMount() {
    this.getListForPage();

    axios
      .ajax({
        url: `${BASEDATA_PATH}/api/open/area/tree`,
        params: {},
      })
      .then(res => {
        res &&
        this.setState({
          areaTree: res.content,
        });
      });

    axios
      .ajax({
        url: `${LOGISTICS_PATH}/web/berthingCompany/all`,
        params: {},
      })
      .then(res => {
        res.content &&
        this.setState({
          insuranceCurrencyList: res.content.list,
        });
      });


  }

  getListForPage = (params: any) =>
    ApiTubro.getListForPage.bind(this)({
      // http://47.99.66.242:8093
      url: `${LOGISTICS_PATH}/web/quotation/trailer?type=1`,
      params: this.page,
    });

  async getlocalfee(pamars) {
    let res = await axios.ajax({
      url: `${LOGISTICS_PATH}/web/feeDetail?type=1&_channelType=ajax`,
      params: {freightId: pamars.id},
    });
    res.content &&
    this.setState({
      localfeesData: res.content.localFeeList,
    });
  }

  handleSubmit = () => {
    const {
      getFieldDecorator,
      getFieldsError,
      getFieldsValue,
      setFieldsValue,
      validateFields,
      validateFieldsAndScroll,
      isFieldValidating,
    } = this.props.form;
    this.props.form.validateFields((err, values) => {
      this.page.page = 1;
      let province = values.area[0];
      let city = values.area[1];
      let district = values.area[2];
      let street = values.area[3];


      this.page = {
        ...this.page,
        ...values,
        // loadingPort: 14659,
        // destinationPort: '',
        province,
        city,
        district,
        street,
        page: 1,
        size: 10,
      };
      this.getListForPage();
      this.setState({
        loadingTableisHide: false,
      });
    });
  };

  render() {
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        md: {span: 4},
      },
      wrapperCol: {
        xs: {span: 24},
        md: {span: 19},
      },
    };
    const trailerList = [
      {value: 'airTransport', name: '空运'},
      {value: 'seaTransport', name: '海运'},
      {value: 'trailerTransport', name: '拖车'},
      {value: 'express', name: '快递'},
      {value: 'Railway', name: '铁路'},
    ];
    const {
      getFieldDecorator,
      setFieldsValue,
      validateFields,
      validateFieldsAndScroll,
    } = this.props.form;
    return (
      <Card>
        <PageHeaderWrapper title="">
          <Card>
            <Row>
              <Col xs={24} lg={12} xl={8}>
                <FormItem label="运输类型" {...formItemLayout}>
                  {getFieldDecorator('transportType', {
                    initialValue: this.state.transportDefaultType,
                  })(
                    <Select
                      style={{width: '100%'}}
                      showSearch
                      placeholder="请选择币种"
                      optionFilterProp="children"
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                      onChange={e => {
                        this.setState({transportDefaultType: e});
                        if (e == 'seaTransport') {
                          this.props.history.push({pathname: '/service/logistics/sea-transport'});
                        } else if (e == 'airTransport') {
                          this.props.history.push({pathname: '/service/logistics/air-transport'});
                        } else if (e == 'trailer') {
                          this.props.history.push({
                            pathname: '/service/logistics/trailer-transport',
                          });
                        }
                      }}
                    >
                      {trailerList.map(item => (
                        <Option value={item.value}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </FormItem>
              </Col>

              <Col xs={24} lg={12} xl={8}>
                <FormItem label="启运港" {...formItemLayout}>
                  {getFieldDecorator('loadingPort', {
                    initialValue: this.state.loadingPort,
                  })(
                    <AutoSearch
                      placeholder="请输入启运港"
                      onChange={(value: any, options) => {
                        console.log(value);
                        this.setState({loadingPort: value});
                      }}
                      url={`${LOGISTICS_PATH}/web/port/nameType?portType=1`}
                      style={{width: '100%'}}
                    />,
                  )}
                </FormItem>
              </Col>

              <Col xs={24} lg={12} xl={8}>
                <FormItem label="目的港" {...formItemLayout}>
                  {getFieldDecorator('destinationPort', {
                    initialValue: this.state.destinationPort,
                  })(
                    <AutoSearch
                      placeholder="请输入目的港"
                      onChange={(value: any) => this.setState({destinationPort: value})}
                      url={`${LOGISTICS_PATH}/web/port/nameType?portType=1`}
                      style={{width: '100%'}}
                    />,
                  )}
                </FormItem>
              </Col>

              <Col xs={24} lg={12} xl={8}>
                <FormItem label="船司" {...formItemLayout}>
                  {getFieldDecorator('berthingId', {
                    initialValue: '',
                  })(
                    <Select
                      showSearch
                      placeholder="请选择币种"
                      optionFilterProp="children"
                      style={{width: '100%'}}
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {this.state.insuranceCurrencyList.map(item => (
                        <Option value={item.id}>{item.berthingName}</Option>
                      ))}
                    </Select>,
                  )}
                </FormItem>
              </Col>

              <Col xs={24} lg={12} xl={8}>
                <FormItem label="区域" {...formItemLayout}>
                  {getFieldDecorator('area', {
                    initialValue: '',
                  })(
                    <Cascader
                      placeholder="请选择区域"
                      options={this.state.areaTree}
                      loadData={selectedOptions => {
                        const targetOption = selectedOptions[selectedOptions.length - 1];
                        targetOption.loading = true;
                        axios
                          .ajax({
                            url: `${BASEDATA_PATH}/api/open/streets/${targetOption.value}`,
                            params: {districtCode: targetOption.value},
                          })
                          .then(res => {
                            targetOption.loading = false;
                            let streetsList = res.content;
                            streetsList.map(item => {
                              item.label = item.streetsName;
                              item.value = item.streetsCode;
                            });
                            targetOption.children = streetsList;
                            this.setState({cascaderOptions: [...this.state.cascaderOptions]});
                          });
                      }}
                      onChange={(value, selectedOptions) =>
                        console.log(value, selectedOptions, 'value, selectedOptions')
                      }
                      changeOnSelect
                      style={{width: '100%'}}
                    />,
                  )}
                </FormItem>
              </Col>

              <Col xs={24} lg={12} xl={8}>
                <FormItem label=" " colon={false} {...formItemLayout}>
                  {getFieldDecorator('berthingId', {
                    initialValue: '',
                    rules: [],
                  })(
                    <>
                      <Button type="primary" onClick={this.handleSubmit}>
                        查询
                      </Button>
                      <Button style={{marginLeft: 10}}>重置</Button>
                    </>,
                  )}
                </FormItem>
              </Col>
            </Row>

            <div className="content-wrap">
              {this.state.transportDefaultType == 'trailerTransport' && (
                <ETable
                  // rowSelection="radio"
                  columns={this.Columns}
                  updateSelectedItem={Utils.updateSelectedItem.bind(this)}
                  selectedRowKeys={this.state.selectedRowKeys}
                  // dataSource={this.props.searchList.content.list}
                  dataSource={this.state.pageListData}
                  pagination={this.state.pagination}
                />
              )}
            </div>
          </Card>

          <Modal
            width={800}
            title="本地费用"
            visible={this.state.localFeeListVisable}
            cancelText="取消"
            onCancel={() => {
              this.setState({
                localFeeListVisable: false,
              });
            }}
          >
            <Localfees localfeesData={this.state.localfeesData || []}/>
          </Modal>
        </PageHeaderWrapper>
      </Card>
    );
  }
}

export default Form.create()(trailerTransport);
